package cn.itcast.travel.dao.impl;

import cn.itcast.travel.dao.RouteDao;
import cn.itcast.travel.domain.Route;
import cn.itcast.travel.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.management.RuntimeOperationsException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author CHAI
 * @Date 2022/4/28 21:10
 **/
public class RouteDaoImpl implements RouteDao {
    private JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
    /**
     * select * from user where cid=? limit ?,?
     * limit ?,?  开始索引位置，每页显示的条数
     * */
    @Override
    public List<Route> pageQuery(int cid, int start, int rows, String rname) {
        String sql="select * from tab_route where 1=1 ";
        StringBuilder stringBuilder = new StringBuilder(sql);
        List<Object> list = new ArrayList<>();
        if (cid!=0){
            stringBuilder.append(" and cid = ? ");
            list.add(cid);
        }
        if (rname!=null&&rname.length()>0){
            stringBuilder.append(" and rname like ?");
            list.add("%"+rname+"%");
        }
        stringBuilder.append(" limit ?,? ");
        list.add(start);
        list.add(rows);
        sql=stringBuilder.toString();
        List<Route> query = template.query(sql, new BeanPropertyRowMapper<>(Route.class),list.toArray());

        return query;
    }
    /**
     * 查询总的记录数据
     * 进行模糊查询，这里条件可能存在，可能不存在，需要根据是否使用进行添加条件
     * sql需要进行拼接
     *
     * @param cid 路经名称
     * @param rname
     * @return 总共的数据条数
     * */
    @Override
    public int findTotalCount(int cid, String rname) {
        String sql="select count(*) from tab_route where 1=1 ";
        StringBuilder stringBuilder = new StringBuilder(sql);
        List<Object> list = new ArrayList<>();
        if (cid!=0){
            stringBuilder.append(" and cid=? ");
            list.add(cid);
        }
        if (rname!=null&&rname.length()>0){
            stringBuilder.append(" and rname like ? ");
            list.add("%"+rname+"%");
        }
        sql=stringBuilder.toString();
        int totalCount = template.queryForObject(sql, Integer.class,list.toArray());
        return totalCount;
    }

    @Override
    public Route findOne(int rid) {
        String sql="select * from tab_route where rid=?";
        Route route = template.queryForObject(sql, new BeanPropertyRowMapper<Route>(Route.class), rid);
        return route;
    }

    @Override
    public int findPrice(int rid) {
        String sql="select price from tab_route where rid=?";
        Integer price = template.queryForObject(sql, Integer.class, rid);
        return price;
    }

    @Override
    public int findSid(int rid) {
        String sql="select sid from tab_route where rid=?";
        Integer sid = template.queryForObject(sql,Integer.class, rid);
        return sid;
    }
}
